package video;

import net.semanticmetadata.lire.*;
import org.apache.lucene.analysis.core.WhitespaceAnalyzer;
import org.apache.lucene.index.*;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;

/**
 * User: Mathias Lux, mathias@juggle.at
 * Date: 25.05.12
 * Time: 12:19
 */
public class Searcher {

    public static String INDEX_REPOSITORY = audio.Util.classPath + "indexrepository";//"src/main/resources/indexrepository";
    public static Integer MULTI_PARAMETER = 60;

    public static List<String> searchFromIndex(String imageFilePath, Integer count) throws IOException {
        List<String> colorLayoutList = new ArrayList<String>();
        List<String> edgeHistogramList = new ArrayList<String>();
        List<String> scalableColorList = new ArrayList<String>();
        List<String> returnImageList = new ArrayList<String>();


        count = count == null || count < 1 ? 10 : count;
        if(imageFilePath == null){
            throw  new NoSuchFieldError("Image file path can not be null!");
        }
        File f = new File(imageFilePath);
        BufferedImage img = null;
        if (f.exists()) {
            img = ImageIO.read(f);
        }else {
            System.out.println("Image is not a file or not exists!");
            throw  new NoSuchFieldError("Image is not a file or not exists!");
        }

        IndexReader ir = DirectoryReader.open(FSDirectory.open(new File(INDEX_REPOSITORY)));
        //color layout image searcher
        ImageSearcher searcher = ImageSearcherFactory.createColorLayoutImageSearcher(count*MULTI_PARAMETER);

        System.out.println(ir.numDocs());

        ImageSearchHits hits = searcher.search(img, ir);
        for (int i = 0; i < hits.length(); i++) {
            String fileName = hits.doc(i).getValues(DocumentBuilder.FIELD_NAME_IDENTIFIER)[0];
            System.out.println(hits.score(i) + ": \t" + fileName + ": \t");
            colorLayoutList.add(fileName.substring(37,fileName.indexOf("/output_")));
        }

        //getEdgeHistogramBuilder
        searcher = ImageSearcherFactory.createEdgeHistogramImageSearcher(count * MULTI_PARAMETER);

        System.out.println(ir.numDocs());

        hits = searcher.search(img, ir);
        for (int i = 0; i < hits.length(); i++) {
            String fileName = hits.doc(i).getValues(DocumentBuilder.FIELD_NAME_IDENTIFIER)[0];
            System.out.println(hits.score(i) + ": \t" + fileName + "");
            edgeHistogramList.add(fileName.substring(37,fileName.indexOf("/output_")));
        }

        //getScalableColorBuilder
        searcher = ImageSearcherFactory.createScalableColorImageSearcher(count * MULTI_PARAMETER);

        System.out.println(ir.numDocs());

        hits = searcher.search(img, ir);
        for (int i = 0; i < hits.length(); i++) {
            String fileName = hits.doc(i).getValues(DocumentBuilder.FIELD_NAME_IDENTIFIER)[0];
            System.out.println(hits.score(i) + ": \t" + fileName + ": \t");
            scalableColorList.add(fileName.substring(37, fileName.indexOf("/output_")));
        }

        for(String scalableColor : scalableColorList){
            if(edgeHistogramList.contains(scalableColor) && colorLayoutList.contains(scalableColor)){
                if(!returnImageList.contains(scalableColor)){
                    returnImageList.add(scalableColor);
                }

            }
        }
        int returnCount = count < returnImageList.size() ? count : returnImageList.size();
        return returnImageList.subList(0,count);
    }

    public static void findDuplicates() throws Exception{
        IndexReader reader = DirectoryReader.open(FSDirectory.open(new File("index")));

        System.out.println("num docs = "+reader.numDocs());

        ImageSearcher searcher = ImageSearcherFactory.createColorLayoutImageSearcher(1000);

        ImageDuplicates duplicates = searcher.findDuplicates(reader);

        System.out.println("duplicates num = " + duplicates.length());

        List<String> deleteDocuments = new ArrayList<String>();
        
        for(int i = 0; i < duplicates.length(); i++){
            List<String> duplicate = duplicates.getDuplicate(i);
            System.out.println(duplicate);
            for(int j = 1; j < duplicate.size(); j++){
                deleteDocuments.add(duplicate.get(j));
            }
        }
        System.out.println("delete documents count = " + deleteDocuments.size());
        // Creating an Lucene IndexWriter
        IndexWriterConfig conf = new IndexWriterConfig(Version.LUCENE_40,
                new WhitespaceAnalyzer(Version.LUCENE_40));

    }

    public static void main(String[] args) throws Exception {



        for(String str : searchFromIndex("/media/study/tsinghua/outputframes/test1/output_000006.jpg",3)){
            System.out.println(str);
        };
    }
}
